package redis

import (
	"context"
	"errors"
	"fmt"
	"gin_template/core/setting"
	"strconv"
	"time"

	"go.uber.org/zap"

	"github.com/go-redis/redis/v8"
)

const TOPIC = "__keyevent@0__:expired"

var Rdb *redis.Client
var Ctx = context.Background()

var redisConf = setting.AppConf.RedisConfig
var db, _ = strconv.Atoi(redisConf.Db)

func InitRedis() {
	Rdb = redis.NewClient(&redis.Options{
		Addr:     "121.4.52.233:6379",
		Password: "", // 密码
		DB:       0,  // 数据库
		PoolSize: 20, // 连接池大小
	})
	_, err := Rdb.Ping(Ctx).Result() // PING, <nil>
	if err != nil {
		fmt.Println("connect redis failed:", err)
		return
	}
	fmt.Println("connect redis success")
}

func Set(key string, val string, expiration time.Duration) error {
	zap.L().Info("redis set: ", zap.String(key, val), zap.Any("expiration", expiration))
	err := Rdb.Set(Ctx, key, val, expiration).Err()
	if err != nil {

		return err
	}
	return nil
}

func Get(key string) (string, error) {
	res, err := Rdb.Get(Ctx, key).Result()
	if err != nil {
		if errors.Is(err, redis.Nil) {
			return "", nil
		}
		return "", err
	}
	fmt.Println("get", res)
	return res, nil
}
